package de.slothsoft.wasbinich.swingclient.control;

import java.awt.Component;
import java.awt.Frame;
import java.util.prefs.Preferences;

import javax.swing.JComponent;

import de.slothsoft.commons.swing.ButtonType;
import de.slothsoft.commons.swing.GridBagUtil;
import de.slothsoft.wasbinich.core.database.webservice.AbstractOAuth2Authenticator.Token;
import de.slothsoft.wasbinich.core.database.webservice.AbstractOAuth2Authenticator.User;
import de.slothsoft.wasbinich.core.database.webservice.OAuth2Authenticator;
import de.slothsoft.wasbinich.swingclient.WasBinIchSwingClient;
import de.slothsoft.wasbinich.swingclient.common.LoginDialog;
import de.slothsoft.wasbinich.swingclient.common.SwingUtil;
import de.slothsoft.wasbinich.swingclient.res.Messages;

public class WasBinIchLoginDialog extends LoginDialog {

    private static final long serialVersionUID = 5830373410139065136L;
    private static final String REGISTER_URL = "http://slothsoft.de/user/register";

    private final OAuth2Authenticator oAuth2Authenticator;

    private Token token;

    public WasBinIchLoginDialog(Frame parent, Preferences preferences, OAuth2Authenticator oAuth2Authenticator) {
	super(parent, preferences);
	this.oAuth2Authenticator = oAuth2Authenticator;
    }

    @Override
    protected Component createLoginPanel() {
	JComponent parent = (JComponent) super.createLoginPanel();

	parent.add(SwingUtil.createLink(Messages.getString("LoginDialog.register"), REGISTER_URL),
		GridBagUtil.textFieldDefaults(1, 3));

	return parent;
    }

    @Override
    protected void performClose() {
	if (this.answer == ButtonType.OK) {
	    try {
		this.token = this.oAuth2Authenticator.getAccessToken(new User(this.user.getLogin(), new String(
			this.user.getPassword())));
	    } catch (Exception exception) {
		WasBinIchSwingClient.handleException(exception);
		return;
	    }
	}
	super.performClose();
    }

    public Token getToken() {
	return this.token;
    }

}